/*
 * UrlUtils.java
 * business
 *
 * Created by ChenTao on 2016/11/4.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.utils;

import com.yidiandao.business.constant.Flavor;
import com.yidiandao.business.constant.Preferences;
import com.yidiandao.business.constant.ServerHost;

/** 地址工具类 */
public class UrlUtils {

    /** 获取真正的地址 */
    public static String getTrulyUrl(String url) {
        return ServerHost.getHost() + url;
    }

    public static String jointUrl(String url) {
        return jointCityForUrl(jointTokenForUrl(url));
    }

    private static String jointTokenForUrl(String url) {
        String token = PreferenceUtils.getToken(UIUtils.getContext());
        if (!PreferenceUtils.STRING_DEFAULT.equals(token)) {
            url = jointUrlByParam(url, "token", token);
        }

        return url;
    }

    private static String jointCityForUrl(String url) {
        //登录时注册的city
        String signCity =
                PreferenceUtils.getString(UIUtils.getContext(), Preferences.SIGN_CITY, false);
        //未登录时选择的city
        String selectCity = PreferenceUtils.getString(UIUtils.getContext(), Preferences.CITY, true);

        //是否已登录
        boolean isSign =
                !PreferenceUtils.STRING_DEFAULT.equals(
                        PreferenceUtils.getToken(UIUtils.getContext()));
        String location_city = isSign ? signCity : selectCity;

        return jointUrlByParam(url, "location_city", location_city);
    }

    private static String jointUrlByParam(String url, String key, String value) {
        String and = url.contains("?") ? "&" : "?";
        int index = url.indexOf("#");
        if (index != -1) {
            // 有 # 号，接在 # 号的前面
            url =
                    url.substring(0, index)
                            + and
                            + key
                            + "="
                            + value
                            + url.substring(index, url.length());
        } else {
            // 没有 # 号，接在最后面
            url = url + and + key + "=" + value;
        }
        return url;
    }

    /** 获取默认的地址<b>默认地区：深圳</b> */
    public static String getDefaultUrl(String url) {

        String host = null;
        switch (FlavorUtils.getCurrentFlavor()) {
            // 发开环境
            case Flavor.DEV:
                host = ServerHost.SZ_DEV_HOST + url;
                break;
            // 测试环境
            case Flavor.TEST:
                host = ServerHost.SZ_TEST_HOST + url;
                break;
            // 生产环境
            case Flavor.ALPHA:
                host = ServerHost.SZ_RELEASE_HOST + url;
                break;
        }

        return host;
    }
}
